import { Injectable, Inject } from '@angular/core';
import { App, NavController, ModalController, ViewController } from 'ionic-angular';
import { Storage } from '@ionic/storage';

import { Observable } from 'rxjs/observable';
import { Store } from '@ngrx/store';
import { AppState } from '../entity/appState.model';
import { Login, Auth, Register } from '../entity/user.model';
import * as AuthActions from '../actions/auth.action';
import * as BorrowActions from '../actions/borrow.action';
import * as OrdersActions from '../actions/orders.action';
import * as UserActions from '../actions/user.action';

import * as PageConstant from '../../constant/pageConstant';

import { ToastService } from '../utils/toast.service';
import { LoadingService } from '../utils/loading.service';
import { AlertService } from '../utils/alert.service';

// import { TabsPage } from '../../pages/tabs/tabs';

/*** 授权相关服务
* */
declare const hmcloud;
@Injectable()
export class AuthService {
  constructor(
    private toastCtrl: ToastService,
    private loadingCtrl: LoadingService,
    public storage: Storage,
    private alertCtrl: AlertService,
    private store$: Store<AppState>,
    @Inject('user') private userService,
  )
  { }

  /*** 获取权限store
   * */
  public getAuth(): Observable<Auth>
  {
    return this.store$.select(AppState => AppState.auth);
  }

  /*** 获取通讯录store
  * */
  public getContacts(): Observable<any>
  {
    return this.store$.select(AppState => AppState.contacts);
  }

  /*** 退出到登录页面
  * */
  backToTabPage(appCtrl,navCtrl,modalCtrl)
  {
    appCtrl.getRootNav().setRoot(PageConstant.TabsPage);

    const views= navCtrl.getViews();
    views.forEach(value=>{
      try {
        navCtrl.removeView(value,{
          animate: false
        });

      } catch (err){
      }

    });

    const modal = modalCtrl.create(PageConstant.LoginPage, {},{
      showBackdrop: false,
      enableBackdropDismiss: false,
    });
    modal.present();

    this.storage.get(PageConstant.LoginPage).then((val) => {
      console.log('Your age is', val);
    });
  }

  /*** 退出
   * @param appCtrl : App
   * @param modalCtrl : ModalController
  * */
  public unAuth(appCtrl: App, modalCtrl: ModalController): void
  {
    this.alertCtrl.createMessageAlert('提示','你是否确定退出吗?')
      .then(yes=>{
        if(!yes) return;
        this.userService.logout();
        // 重置全部应用状态
        this.store$.dispatch(new AuthActions.LogoutAction());
        this.store$.dispatch(new UserActions.ResetAuthStoreAction());
        this.store$.dispatch(new BorrowActions.ResetBorrowStoreAction());
        this.store$.dispatch(new OrdersActions.ResetOrderStoreAction());
        appCtrl.getRootNav().setRoot(PageConstant.TabsPage);
        const modal = modalCtrl.create(PageConstant.LoginPage, {},{
          showBackdrop: false,
          enableBackdropDismiss: false,
        });
        modal.present();
    });
  }

  /*** APP进入检查是否为登录状态
   * */
  public checkHasLogin(): Promise<any>
  {
    return new Promise((resolve, reject) => {
      let auth = hmcloud.User.current();
      if (auth){
        this.store$.dispatch(new AuthActions.LoginSuccessAction(auth));
        // 若已登录
        resolve(true);
      }
      resolve(false);
    });

  }

  /*** 登录
   * @param appCtrl 路由控制器
   * @param login: Login { username, password }
   * @param viewCtrl: ViewController
   * */
  public loginWithCredentials(login: Login, appCtrl: App, viewCtrl: ViewController): void
  {
    this.loadingCtrl.create('加载中');
    this.userService.findLogin(login).subscribe(auth => {
      this.store$.dispatch(new AuthActions.LoginSuccessAction(auth));
      // 重置全部应用状态
      this.store$.dispatch(new UserActions.ResetAuthStoreAction());
      this.store$.dispatch(new BorrowActions.ResetBorrowStoreAction());
      this.store$.dispatch(new OrdersActions.ResetOrderStoreAction());
      this.loadingCtrl.closeLoading().then(()=>{
        // 移除标识,设置
        this.storage.remove(PageConstant.LoginPage)
          .then(() => {
            appCtrl.getRootNav().setRoot(PageConstant.TabsPage);
            if(viewCtrl) viewCtrl.dismiss();
          });
      });

    },error=>{
      this.loadingCtrl.closeLoading().then(()=>{
        this.store$.dispatch(new AuthActions.LoginFailedAction(error.message));
        this.toastCtrl.createCenterToast(error.message);
      });

    });
  }

  /*** 注册
   * 1. 检查用户是否注册
   * @param reg 用户注册信息
  * */
  public checkRegister(reg: Register): void
  {
    const { username }= reg;
    this.userService.checkTelephone(username)
      .subscribe(result=>{

      // state 为false代表用户已存在
      if(!result.state){
        this.toastCtrl.createCenterToast(result.message);
        return;
      }

      // 用户未注册,则发送验证码
      this.userService.sendSmsCode(reg.username)
        .subscribe(result=>{
        this.toastCtrl.createCenterToast('验证码发送成功,请注意查收');
      },error=>{
        this.toastCtrl.createCenterToast(error.message);
      });
    },error=>{
      this.toastCtrl.createCenterToast(error.message);
    });
  }

  /*** 注册
   * 2. 增加用户
   * @param reg 用户注册信息
   * @param navCtrl 路由控制器
   * */
  public executeRegister(reg: Register, navCtrl: NavController): void
  {
    this.loadingCtrl.createLoading('正在加载中');

    this.userService.addUser(reg).subscribe(auth=>{
       // 注册成功
      this.store$.dispatch(new AuthActions.RegisterSuccessAction(auth));

       // 保存通讯录
      this.getContacts().first().subscribe(contacts=> {
        let oldArr=[];
        contacts.map(data=>{
          oldArr=[...oldArr,...data.value]
        });
        const arr= oldArr.map(value=>{
          const { name, phone}= value;
          return { name, phone }
        });
        this.userService.saveContactsWhenReg(arr).then(result=> {
          // 此处不处理保存结果
          this.hasRegSuccNext(navCtrl);
        }).catch(err=> {
          // 此处不处理保存结果
          this.hasRegSuccNext(navCtrl);
        })

      });

     },error=>{
      this.loadingCtrl.closeLoading().then(()=>{
        this.toastCtrl.createCenterToast(error.message);
      });
    });
  }

  /*** 注册成功下一步
   * @param navCtrl 路由控制器
  * */
  private hasRegSuccNext(navCtrl: NavController)
  {
    // 此处对返回不做处理
    this.loadingCtrl.closeLoading().then(()=>{

      return this.alertCtrl.createAgreeAlert('注册成功,现在去登录');

    }).then(data=> {
      navCtrl.pop();
    }).catch(error =>{
      this.toastCtrl.createCenterToast(error.message);
    });
  }

  /*** 找回密码
   * 1. 获取验证码
   * @param reg 用户注册信息
   * */
  public sendMsgCodeWhenForget(reg: Register) : void
  {
    const { username }= reg;
    this.userService.sendSmsCodeWhenForget(username)
      .subscribe(result=>{
        this.toastCtrl.createCenterToast('验证码发送成功,请注意查收');
    },error=>{
      this.toastCtrl.createCenterToast(error.message);
    });
  }

  /*** 找回密码
   * 2. 更新密码
   * @param forget 忘记密码表单信息 { username, password, msgCode }
   * @param appCtrl : App
   * @param navCtrl NavController
   * @param modalCtrl ModalController
   * */
  public getBackPassword(forget: Register,appCtrl: App, navCtrl: NavController, modalCtrl: ModalController): void
  {
    this.userService.updatePassword(forget).subscribe(result=>{
      // 若修改成功
      this.store$.dispatch(new AuthActions.UpdatePasswordSuccessAction());
      this.storage.get(PageConstant.LoginPage)
        .then(data => {
          if(data){ // 是登录页面进入
            navCtrl.pop();
            return;
          }
          appCtrl.getRootNav().setRoot(PageConstant.TabsPage);
          const modal = modalCtrl.create(PageConstant.LoginPage, {},{
            showBackdrop: false,
            enableBackdropDismiss: false,
          });
          modal.present();
      });
    },error=>{
      this.toastCtrl.createCenterToast(error.message);
    });
  }

  /*** 修改密码(原密码)
   * @param reset_password 新旧密码
   * @param appCtrl : App
   * @param modalCtrl : ModalController
  * */
  public updatePwdByOldPwd(reset_password: any, appCtrl: App, modalCtrl: ModalController): void
  {
    this.loadingCtrl.create('加载中');
    this.userService.updatePwdByOldPwd(reset_password)
      .subscribe(result => {
        this.userService.logout();
        // 若修改成功(修改Auth)
        this.store$.dispatch(new AuthActions.UpdatePasswordSuccessAction());

        this.loadingCtrl.closeLoading().then(()=>{
          appCtrl.getRootNav().setRoot(PageConstant.TabsPage);

          const modal = modalCtrl.create(PageConstant.LoginPage, {},{
            showBackdrop: false,
            enableBackdropDismiss: false,
          });
          modal.present();
        });


    },error =>{
        this.loadingCtrl.closeLoading().then(()=>{
          this.toastCtrl.createCenterToast(error.message || error);
        })
    });
  }

}
